package com.lee.sshclient.plugin;

import com.lee.sshclient.ShellCallback;
import com.lee.sshclient.ShellClient;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by le on 2016/1/18.
 */
public class SSHClientPlugin extends CordovaPlugin {

    Map<String, ShellClient> shellClientMap = new HashMap<>();

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        if ("connect".equals(action)) {
            String name = args.getString(0);
            String host = args.getString(1);
            int port = Integer.parseInt(args.getString(2));
            String user = args.getString(3);
            String password = args.getString(4);

            final ShellClient shellClient = new ShellClient(user, password, host, port, new ShellCallback.Callback() {
                @Override
                public void execute(String response) {
                    System.out.println("Response: " + response + "EOF");
                    PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, response);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);
                }
            });

            shellClientMap.put(name, shellClient);

            SSHConnectRunnable sshConnect = new SSHConnectRunnable(shellClient, callbackContext);
            cordova.getThreadPool().execute(sshConnect);
            return true;
        } else if("execute".equals(action)) {
            String name = args.getString(0);
            final String command = args.getString(1);
            ShellClient shellClient = shellClientMap.get(name);
            if(shellClient == null) {
                callbackContext.error("连接不存在");
            } else {
                cordova.getThreadPool().execute(new SSHExecuteRunnable(shellClient, callbackContext, command));
            }
            return true;
        } else if("close".equals(action)) {
            String name = args.getString(0);
            ShellClient shellClient = shellClientMap.get(name);
            shellClient.disconnect();
            callbackContext.success("成功关闭终端");
            return true;
        } else {
            return false;
        }
    }
}
